package com.liwq.base.bolckqueue;

import java.time.LocalDateTime;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author : liwq
 * @version : 1.0
 * @date : 2023/2/22
 * 模拟生产者消费者，一个变量初始值为0，两个线程交替操作，一个加一一个减一，交替来5轮
 **/
class ShareData {
    private int number = 0;
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    public void increment() {
        try {
            //当变量不为0的时候，生产者不能生产；只有变量为1了，才可以生产数据
            lock.lock();
            while (number != 0) {
                condition.await();
            }
            //生产者工作
            number++;
            System.out.println(Thread.currentThread().getName() + " 生成" + number);
            condition.signalAll();

        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }

    public void decrement() {
        try {
            //当变量为0的时候，消费者不能工作
            lock.lock();
            while (number == 0) {
                condition.await();
            }
            //生产者工作
            number--;
            System.out.println(Thread.currentThread().getName() + "消费" + number);
            condition.signalAll();

        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }


}

public class ProdConsumerTraditionDemo {

    public static void main(String[] args) {
        ShareData shareData = new ShareData();


        //t1 线程生产
        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                shareData.increment();
            }

        }, "t1").start();

        //t2线程消费

        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                shareData.decrement();
            }

        }, "t2").start();
    }


}
